<template>
  <div class="capa-edit-wrapper">
    <div class="progress-wrap">
      <div class="now-progress">
        <el-steps :active="currentIndex" align-center>
          <!-- <el-step title="投诉处理与报告" description="2020/10/10 14:00:39"></el-step>
                <el-step title="评估影响" description="未开始"></el-step>
                <el-step title="纠正与预防措施" description="未开始"></el-step>
                <el-step title="主管复核" description="未开始"></el-step>
                <el-step title="生效" description="未开始"></el-step> -->
          <!-- :status="item.status === '1' ? 'success' : 'wait'" -->
          <el-step
            v-for="(item, index) in processData"
            :key="index"
            :title="item.process_name"
            :description="item.process_desc"
            :status="item.status === '2' ? 'error' : undefined"
          ></el-step>
        </el-steps>
      </div>
    </div>

    <Complaint
      :detailData="detailData"
      :statusData="processData[0]"
      :mode="calcMode(0)"
    ></Complaint>
    <Evaluate
      :detailData="detailData"
      :statusData="processData[1]"
      :mode="calcMode(1)"
      v-if="currentIndex >= 1"
    >
    </Evaluate>
    <Measures
      :detailData="detailData"
      :statusData="processData[2]"
      :mode="calcMode(2)"
      v-if="currentIndex >= 2"
    >
    </Measures>

    <div
      class="operation-footer"
      v-if="currentIndex == 3 || currentIndex == 4 || currentIndex == 5"
    >
      <div class="footer-wrap">
        <el-button size="small" @click="handleClickClose">关闭</el-button>
        <template v-if="currentIndex == 3 || currentIndex == 4">
          <el-button
            v-show="isReviewr"
            size="small"
            type="primary"
            @click="handleOperation('1')"
            >通过</el-button
          >
          <el-button
            v-show="isReviewr"
            size="small"
            type="primary"
            @click="handleOperation('2')"
            >驳回</el-button
          >
        </template>
        <!-- <el-button v-show="currentIndex == 5" size="small" type="primary"
                    @click="handleOperation('3')">生成CAPA报告</el-button> -->
        <el-button
          v-show="currentIndex == 5"
          size="small"
          type="primary"
          @click="handleOperation('4')"
          >导出CAPA报告</el-button
        >
      </div>
    </div>
    <el-dialog
      title="审核"
      width="500px"
      :close-on-click-modal="false"
      v-if="auditDialogVisible"
      :modal-append-to-body="false"
      @close="handleCloseAuditDialog"
      :visible="auditDialogVisible"
    >
      <el-form
        :model="auditForm"
        ref="ruleForm"
        style="width: 400px"
        label-width="80px"
      >
        <el-form-item label="审核意见" prop="option">
          <el-input type="textarea" v-model="auditForm.option"></el-input>
        </el-form-item>
        <el-form-item label="驳回节点" prop="process_id" v-if="type === '2'">
          <el-select v-model="auditForm.process_id" filterable clearable>
            <el-option
              v-for="(process, index) in PROCESS_NAME"
              :key="index"
              :label="process"
              :value="index + ''"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" style="text-align: center; padding-top: 20px">
        <el-button @click="handleCloseAuditDialog">取 消</el-button>
        <el-button type="primary" @click="handleAuditOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Complaint from "./components/complaint.vue";
import Evaluate from "./components/evaluate.vue";
import Measures from "./components/measures.vue";
import {
  CapaDetail,
  CapaCheck,
  CapaReject,
  CapaGenerateReport,
  CapaExportReport,
} from "@/api/qms";
import moment from "moment";
import { downloadFile } from "@/utils/mUtils";

export default {
  name: "capaEdit",
  components: { Complaint, Evaluate, Measures },
  props: [],
  data() {
    return {
      processData: [
        {
          process_name: "投诉处理与报告",
          process_desc: "未开始",
          status: "1",
        },
        {
          process_name: "评估影响",
          process_desc: "未开始",
        },
        {
          process_name: "纠正与预防措施",
          process_desc: "未开始",
        },
        {
          process_name: "主管复核",
          process_desc: "未开始",
        },
        {
          process_name: "生效",
          process_desc: "未开始",
        },
      ],
      currentIndex: 0,
      detailData: null,
      mode: "",
      auditForm: {
        option: "",
        process_id: "2",
      },
      auditDialogVisible: false,
      type: "",
      PROCESS_NAME: ["投诉处理与报告", "评估影响", "纠正与预防措施"],
    };
  },
  computed: {
    calcMode() {
      return function (index) {
        if (this.mode === "detail") return "detail";
        if (this.currentIndex == index) {
          if (this.detailData) {
            return "edit";
          } else {
            return "add";
          }
        } else {
          return "detail";
        }
      };
    },
    isReviewr() {
      const { user_id } = this.$store.state.user || {};
      const userIds = (this.detailData.check_leader || []).map(
        (item) => item.user_id
      );
      return userIds.includes(user_id + "");
    },
  },
  watch: {
    $route: {
      handler: function () {
        this.handleChangeMode();
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    const PROCESS_NAME = [
      "投诉处理与报告",
      "评估影响",
      "纠正与预防措施",
      "主管复核",
      "生效",
    ];
    const id = this.$route.query.id;
    this.mode = this.$route.query.mode || "add";
    if (this.mode === "detail" || this.mode === "edit") {
      CapaDetail({ id }).then((res) => {
        this.processData = res.data.process;
        this.processData.forEach((item) => {
          item.process_name = PROCESS_NAME[item.process_id];
          item.process_desc = [
            "未开始",
            moment(item.process_time * 1000).format("YYYY-MM-DD HH:mm:ss"),
            "已驳回",
          ][item.status];
        });

        this.detailData = res.data;
        if (this.processData.every((item) => item.status === "1")) {
          this.currentIndex = 5;
        } else {
          const rejectIndex = this.processData.findIndex(
            (item) => item.status === "2"
          );
          this.currentIndex =
            rejectIndex > -1
              ? rejectIndex
              : this.processData.findIndex((item) => item.status === "0");
        }
        // 主管复核1是进行中，相当于0 currentIndex是4，实际是3
        if (
          (this.processData[3] || {}).status === "1" &&
          (this.processData[4] || {}).status === "0"
        ) {
          this.processData[3].process_desc = "进行中";
          this.currentIndex = 3;
        }
      });
    }
  },
  methods: {
    handleClickClose() {
      this.$router.go(-1);
    },
    handleCloseAuditDialog() {
      this.auditDialogVisible = false;
    },
    handleAuditOk() {
      if (this.type === "1") {
        CapaCheck({
          id: this.detailData.id,
          opinion: this.auditForm.option,
        }).then((res) => {
          if (res.code === 10000) {
            this.$message({
              type: "success",
              message: "审核通过",
            });
            this.handleCloseAuditDialog();
            setTimeout(() => {
              this.$router.push({
                name: "capaList",
              });
            }, 200);
          }
        });
      } else if (this.type === "2") {
        if (!this.auditForm.option) {
          this.$message({
            type: "warning",
            message: "请填写审批意见",
          });
          return;
        }
        CapaReject({
          id: this.detailData.id,
          opinion: this.auditForm.option,
          process_id: this.auditForm.process_id,
        }).then((res) => {
          if (res.code === 10000) {
            this.$message({
              type: "success",
              message: "驳回成功",
            });
            this.handleCloseAuditDialog();
            setTimeout(() => {
              this.$router.push({
                name: "capaList",
              });
            }, 200);
          }
        });
      }
    },
    handleOperation(type) {
      switch (type) {
        case "1":
          this.type = type;
          this.auditDialogVisible = true;
          break;
        case "2":
          this.type = type;
          this.auditDialogVisible = true;
          break;
        case "3":
          CapaGenerateReport({
            id: this.detailData.id,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "warning",
                message: "报告生成成功，可以导出啦",
              });
            }
          });
          break;
        case "4":
          CapaExportReport({
            id: this.detailData.id,
          }).then((res) => {
            if (res.code === 10000) {
              downloadFile(
                `CAPA报告_${this.detailData.capa_no}`,
                res.data.loaded_url
              );
            }
          });
          break;

        default:
          break;
      }
    },
    handleChangeMode() {
      if (this.mode === "add") {
        this.initNewVersionFile();
        this.setExpireTime();
      } else if (this.mode === "detail" || this.mode === "edit") {
        this.getDetail();
      }
    },
    getDetail() {
      const PROCESS_NAME = [
        "投诉处理与报告",
        "评估影响",
        "纠正与预防措施",
        "主管复核",
        "生效",
      ];
      const id = this.$route.query.id;
      this.mode = this.$route.query.mode;
      CapaDetail({ id }).then((res) => {
        this.processData = res.data.process;
        this.processData.forEach((item) => {
          item.process_name = PROCESS_NAME[item.process_id];
          // moment(value).format("YYYY-MM-DD HH:mm:ss");
          item.process_desc =
            item.status === "1"
              ? moment(item.process_time * 1000).format("YYYY-MM-DD HH:mm:ss")
              : "未开始";
        });
        this.detailData = res.data;
        this.currentIndex = this.processData.findIndex(
          (item) => item.status === "0"
        );
        // console.log(this.currentIndex, 'crrr');
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.capa-edit-wrapper {
  background: #f0f2f5;

  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: 20px;

  .form-container {
    padding: 20px;
  }

  .rule_title {
    // background: red;
    display: flex;
    align-items: center;
    padding-bottom: 18px;
    padding-top: 8px;
    font-size: 14px;
    font-weight: bold;
    justify-content: space-between;

    .title-l {
      display: flex;
      align-items: center;
    }

    .icon_left {
      display: inline-block;
      width: 6px;
      height: 16px;
      background: #f1a357;
      margin-right: 6px;
    }

    .icon-right {
    }
  }

  .range_tab {
    width: 100%;
    height: 30px;
    background: #f2f3f5;
    font-weight: bold;
    line-height: 30px;
    padding-left: 12px;
    margin-bottom: 16px;
    color: #6d6e72;
    font-size: 14px;
  }

  /deep/.operation-footer {
    position: fixed;
    width: calc(100% - 180px);
    bottom: 0;
    background: white;
    box-sizing: border-box;
    padding: 15px 0;
    box-shadow: 0px -10px 20px -10px rgba(0, 0, 0, 0.07);
    z-index: 100;
    left: 180px;

    .footer-wrap {
      text-align: center;
    }
  }

  .progress-wrap {
    background: #fff;

    .now-progress {
      padding: 30px 40px;
    }
  }

  /deep/.capa-card {
    box-sizing: border-box;
    background: #fff;
    margin: 8px;
    border-radius: 5px;
    padding: 10px;
  }

  /deep/.capa-divider {
    margin-top: 6px !important;
  }
}
</style>